package com.woniu.service;

import com.woniu.dto.UserDto;
import com.woniu.entity.UserInfo;
import com.woniu.feign.UserFeign;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

@Service
public class SecurityUserDetailsService implements ReactiveUserDetailsService {
    @Resource
    UserFeign userFeign;
    @Resource
    PasswordEncoder passwordEncoder;

    @Override
    public Mono<UserDetails> findByUsername(String username) {
        UserDto user = userFeign.findByUsername(username);
        return user == null
                ? Mono.error(new UsernameNotFoundException("User not found with username: " + username))
                : Mono.just(new UserInfo(user.getId(), username, passwordEncoder.encode(user.getPassword()),
                AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", user.getAuthCodes()))));
    }
}


